<?php

/**
 * @author Thibaut Cromphaut, Gaïtano Boeraeve, Mathias Helin, Dimitry Dierickx
 * @copyright  Copyright (c) 2011 Artevelde University College Ghent 
 */

class Application_Model_AnnouncementMapper extends Ahs_Model_Mapper
{

    public function __construct(array $options = null)
    {
        parent::__construct($options);
        $this->DbTableName = 'Application_Model_DbTable_Announcements';
        $this->PropertiesMap = array
        (
            "Id"            => "announcement_id",
            "Title"         => "announcement_title",
            "Text"          => "announcement_text",
            "CreationDate"  => "announcement_creationdate",
            "ModifiedDate"  => "announcement_modifieddate",
            "DeletedDate"   => "announcement_deleteddate",
            "Active"        => "announcement_active",
            "AuthorId"      => "users_user_id",
            "CourseId"      => "courses_course_id",
        );
    }
    
    /**
     * Get all announcements
     * @return Array(Application_Model_Announcement)
     */
    public function fetchAll()
    {        
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where(''.$this->getColumn('DeletedDate').' IS NULL');
        $rows = $table->fetchAll($select);
        return $this->_toAnnouncements($rows);
    }

    /**
     * Get an announcement by its ID
     * 
     * @param integer $id
     * @return Application_Model_Announcement
     */
    public function fetchById($id)
    {
        $row = $this->getDbTable()->fetchRow(array(''.$this->getColumn('Id').' = ?' => $id));
        return $this->_toAnnouncement($row);
    }
    
    /**
     * Search announcements by name
     * 
     * @param type $name
     * @return Array(Application_Model_Announcement) 
     */
    public function fetchByName($name)
    {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where(
                    ''.$this->getColumn('Title').' LIKE :name'
                        . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                )
               ->bind( array(':name' => "%{$name}%") )
               ->order(''.$this->getColumn('Title').' ASC')
               ->limit(10);
        $rows = $table->fetchAll($select);
        return $this->_toAnnouncements($rows);
    }
    
    /**
     * Get all announcements by name for an author
     * 
     * @return Array(Application_Model_Announcement)
     */
    public function fetchByNameAndAuthorId($announcement_name, $author_id)
    {
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->where(
                    ''.$this->getColumn('Title').'  LIKE :title'                    
                       . ' AND ' .
                    ''.$this->getColumn('AuthorId').' = :id'
                       . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->bind(array(':title' => "%{$announcement_name}%", ':id' => $author_id))
               ->order(''.$this->getColumn('Title').' ASC');
        $rows = $table->fetchAll($select);
        return $this->_toAnnouncements($rows);
    }
    
    /**
     * Get announcements by course
     * 
     * @param integer $course_id
     * @param integer $page_nr      If you wish to use paging, pass the page-number. To disable paging, 
     *                              pass null as value (default) and return all rows.
     * @param integer $nr_results   The number of results per page, defaults to 10.
     * @return Array(Application_Model_Announcement)
     */
    public function fetchByCourseId($course_id, $page_nr=null, $nr_results=10)
    {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->where(
                    ''.$this->getColumn('CourseId').' = :id'
                        . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                )
                ->bind(array(':id' => $course_id))
                ->order(''.$this->getColumn('CreationDate').' DESC');
        
        if($page_nr != null && $page_nr > 0)
            $select->limitPage($page_nr, $nr_results);
        
        $rows = $table->fetchAll($select);
        return $this->_toAnnouncements($rows);
    }
    
    /**
     * Get course announcements for a given user
     * 
     * @param integer $user_id
     * @param integer $page_nr      If you wish to use paging, pass the page-number. To disable paging, 
     *                              pass null as value (default) and return all rows.
     * @param integer $nr_results   The number of results per page, defaults to 10.
     * @return Array(Application_Model_Announcement)
     */
    public function fetchByUserId($user_id, $page_nr=null, $nr_results=10)
    {
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->from(array('a' => 'announcements'))->joinInner(array('uhc' => 'users_has_courses'),'uhc.courses_course_id=a.courses_course_id')
               ->where(
                    'uhc.users_user_id = :user_id'
                       . ' AND ' .
                    'a.'.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->bind(array(':user_id' => $user_id))
               ->order(''.$this->getColumn('CreationDate').' DESC');
        
        if($page_nr != null && $page_nr > 0)
            $select->limitPage($page_nr, $nr_results);
        
        $rows = $table->fetchAll($select);     
        return $this->_toAnnouncements($rows);
    }
    
    /**
     * Get all annoucements for an author
     * 
     * @param integer $author_id
     * @param integer $page_nr      If you wish to use paging, pass the page-number. To disable paging, 
     *                              pass null as value (default) and return all rows.
     * @param integer $nr_results   The number of results per page, defaults to 10.
     * @return Array(Application_Model_Annoucement)
     */
    public function fetchByAuthorId($author_id, $page_nr=null, $nr_results=10)
    {
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->where(
                    ''.$this->getColumn('AuthorId').' = :id'
                       . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->bind(array(':id' => $author_id))
               ->order(''.$this->getColumn('CreationDate').' DESC');
        
        if($page_nr != null && $page_nr > 0)
            $select->limitPage($page_nr, $nr_results);
        
        $rows = $table->fetchAll($select);
        return $this->_toAnnouncements($rows);
    }
    
    /**
     * Get the total number of books
     * 
     * @return integer
     */
    public function getCount()
    {
        $ids    = array();
        
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($table, array('count(*) as count'));
        $select->where(''.$this->getColumn('DeletedDate').' IS NULL');
        
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;
    }
    
    /**
     * Get the total number of announcements for this user
     * 
     * @param integer $user_id
     * @return integer
     */
    public function getCountByUserId($user_id)
    {
        $ids    = array();
        
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->from($table, array('count(*) as count'));
        $select->joinInner(array('uhc' => 'users_has_courses'),'uhc.courses_course_id=announcements.courses_course_id')
               ->where(
                    'uhc.users_user_id = :user_id'
                       . ' AND ' .
                    'announcements.'.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->bind(array(':user_id' => $user_id));
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;
    }
    
    public function getCountByAuthorId($author_id)
    {
        $table = $this->getDbTable();
        $select = $table->select()->setIntegrityCheck(false);
        $select->from($table, array('count(*) as count'));
        $select->where(
                    ''.$this->getColumn('AuthorId').' = :id'
                       . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                 )
               ->bind(array(':id' => $author_id));
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;
    }
    
    /**
     * Get the total number of announcements for this course
     * 
     * @param integer $course_id
     * @return integer
     */
    public function getCountByCourseId($course_id)
    {
        $table = $this->getDbTable();
        $select = $table->select();
        $select->from($table, array('count(*) as count'));
        $select->where(
                    ''.$this->getColumn('CourseId').' = :id'
                        . ' AND ' .
                    ''.$this->getColumn('DeletedDate').' IS NULL'
                )
                ->bind(array(':id' => $course_id));
        $rows = $table->fetchAll($select);
        
        return $rows[0]->count;
    }
    
    /**
     * Save an announcement
     *
     * @param Application_Model_Announcement $announcement
     */
    public function save(Application_Model_Announcement $announcement)
    {
        $announcement_id    = $announcement->Id;
        
        $data = $this->_getTableValues($announcement, array("Id"));
        $data[$this->getColumn("ModifiedDate")] = new Zend_Db_Expr('NOW()');
        
        if (null == $announcement_id)
        {
            
            // Set some default values
            $data[$this->getColumn("CreationDate")] = new Zend_Db_Expr('NOW()');
            $data[$this->getColumn("AuthorId")]     = $this->getLoggedInUserId();
        
            $announcement_id = $this->getDbTable()->insert($data);
        }
        else
        {
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $announcement_id));
        }
        
        return $announcement_id;
    }
    
    /**
     * Delete an announcement by id
     *
     * @param integer $id
     */
    public function delete($id)
    {   
        if (null != $id)
        {
            $data[$this->getColumn('DeletedDate')] = new Zend_Db_Expr('NOW()');
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $id));
        }
    }
    
    /**
     * Undelete an announcement by id
     *
     * @param integer $id
     */
    public function undelete($id)
    {   
        if (null != $id)
        {
            $data[$this->getColumn('DeletedDate')] = new Zend_Db_Expr('NULL');
            $this->getDbTable()->update($data, array(''.$this->getColumn('Id').' = ?' => $id));
        } 
    }
    
    /**
     * Convert a row to object
     * 
     * @param Zend_Db_Table_Row_Abstract $row
     * @return Application_Model_Announcement 
     */
    private function _toAnnouncement(Zend_Db_Table_Row_Abstract $row = null)
    {
        // Create our object
        $object = new Application_Model_Announcement();
        
        // Only go on if we actually have a row
        if($row)
        {
            // We have a propertiesmap, let's try to map it back to an object
            foreach($this->PropertiesMap as $key=>$column)
            {
                if(isset($row[$column]))
                    $object->$key      = $row[$column];
            }
        }

        return $object;
    }

    /**
     * Convert a rowset to an array of objects
     * 
     * @param Zend_Db_Table_Rowset_Abstract $rows
     * @return Array(Application_Model_Announcement)
     */
    private function _toAnnouncements(Zend_Db_Table_Rowset_Abstract $rows = null)
    {
        $results = array();
        if ($rows)
        {
            foreach ($rows as $row)
            {
                $results[] = $this->_toAnnouncement($row);
            }
        }
        return $results;
    }
}